//
//  UITextField.swift
//  
//
//  Created by tangbl93 on 2021/2/6.
//

import UIKit

public extension UITextField {
    
    /// leading view margin
    var yx_leadingMargin: CGFloat {
        get {
            let leadingView = yx_isRTL ? rightView : leftView
            let displayMode = yx_isRTL ? rightViewMode : leftViewMode
            
            if displayMode == .always {
                return leadingView?.yx_width ?? 0
            }
            return 0
        }
        set {
            
            var leadingView: UIView? = nil
            var displayMode: UITextField.ViewMode = .never
            
            if newValue > 0 {
                displayMode = .always
                leadingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: 0))
            }
            
            if yx_isRTL {
                rightView = leadingView
                rightViewMode = displayMode
            } else {
                leftView = leadingView
                leftViewMode = displayMode
            }
        }
    }
    
    /// traling view margin
    var yx_tralingMargin: CGFloat {
        get {
            let tralingView = yx_isRTL ? leftView : rightView
            let displayMode = yx_isRTL ? leftViewMode : rightViewMode
            
            if displayMode == .always {
                return tralingView?.yx_width ?? 0
            }
            return 0
        }
        set {
            
            var tralingView: UIView? = nil
            var displayMode: UITextField.ViewMode = .never
            
            if newValue > 0 {
                displayMode = .always
                tralingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: 0))
            }
            
            if yx_isRTL {
                leftView = tralingView
                leftViewMode = displayMode
            } else {
                rightView = tralingView
                rightViewMode = displayMode
            }
        }
    }
}
